/*
 * @Author: rainbow
 * @Date: 2021-09-Sa 08:10:31
 * @Last Modified by:   rainbow
 * @Last Modified time: 2021-09-Sa 08:10:31
 */
const Db = require('./Db');
const O = require('../utils/O');

// 公用 Api
// 无需事务的话 最好 即开即关
const Api = {
  ret: (res, conn='') => {
    conn.release && conn.release()
    return res;
  },
  add: async(conn,SQL,user) => {
    const sql = SQL.insertObj(user)
    // console.log('sql',sql);
    return Db.getInsertId(
      await conn.execute(sql.sql, sql.value))
  },
  /**
   * @return  <mixed>{id:number}|false</mixed>
   */
  getById: async (conn,SQL, id, col = '') => {
    // console.log('sql', SQL.selectOne('', 'id=?'));
    // id=字符串 也可执行
    if(O.isNumberString(id, ':id')) id = parseInt(id)
    return Db.getRowWithIdOrFalse(
      await conn.execute(SQL.selectOne(col, 'id=?'), [id]));
  },
  queryCount: async (conn,SQL, params = [], col='',where='',last='') => {
    const [rows, count] = await Promise.all([
      conn.execute(SQL.select(col, where, last), params),
      conn.execute(SQL.selectCount(where), params),
    ])
    return {
      list: Db.getRows(rows),
      count: Db.getCount(count)
    }
  },
  query: async (conn,SQL, params = [], col = '', where = '', last = '') => {
    return Db.getRows(
      await conn.execute(SQL.select(col, where, last), params))
  },
  delById: async (conn,SQL,id) => {
    if (O.isNumberString(id, ':id')) id = parseInt(id)
    return Db.getAffects(
      await conn.execute(SQL.delete('id=?'), [id]))
  },
  del: async (conn,SQL,obj) => {
    const sql = SQL.deleteObj(obj)
    return Db.getAffects(
      await conn.execute(sql.sql, sql.value))
  },
  upd: async (conn,SQL,setObj, whereObj,last='') => {
    const sql = SQL.updateObj(setObj, whereObj,last)
    return Db.getAffects(
      await conn.execute(sql.sql, sql.value))
  },
  updById: async (conn,SQL,user) => {
    const sql = SQL.updateObjById(user)
    // console.log('sql ',sql);
    // const res = await conn.execute(SQL.update('name=?,nick=?', 'id=?'), [user.name, user.nick, user.id])
    // return Db.getAffects(res)
    return Db.getAffects(
      await conn.execute(sql.sql, sql.value))
  },
}
module.exports = Api